<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/8/14
 * Time: 17:30
 */
namespace App\Api\Controllers\Weixin;


use App\Api\Controllers\BaseController;
use App\Api\Controllers\Config\WeixinConfigController;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;


class WxCardController extends BaseController
{

    //curl请求
    function https_request($url, $data = '', $type = 'get', $res = 'json')
    {
        //1.初始化curl
        $curl = curl_init();
        //2.设置curl的参数
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if (isset($data['media'])) {
            if (class_exists('\CURLFile')) { // 这里用特性检测判断php版本
                $data['buffer'] = new \CURLFile(realpath($data['media']));
            } else {
                if (defined('CURLOPT_SAFE_UPLOAD')) {
                    curl_setopt($curl, CURLOPT_SAFE_UPLOAD, FALSE);
                }
            }
//        if (class_exists('\CURLFile')) { // 这里用特性检测判断php版本
//            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
//            $data = ['media' => new \CURLFile(realpath($data['media']))];
//        } else {
//            if (defined('CURLOPT_SAFE_UPLOAD')) {
//                curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
//                $data = ['media' => '@' . realpath($data['media'])];
//            }
//        }
        }
        if ($type == 'post'){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, 320));
        }

        //3.采集
        $output = curl_exec($curl);
        //var_dump(curl_getinfo($curl));
        //4.关闭
        curl_close($curl);
        if ($res == 'json') {
            return json_decode($output, true);
        }
    }


    //获取微信access_token
    function get_access_token($config_id = '1234')
    {
        $config = new WeixinConfigController();
        $config_obj = $config->weixin_config_obj($config_id);
        if (!isset($config_obj->app_id) || !isset($config_obj->app_secret)) {
            return json_encode([
                'status' => '2',
                'message' => '微信参数未配置'
            ]);
        }

        $appid = $config_obj->app_id;
        $secret = $config_obj->app_secret;

        if (Cache::has($appid)) {
            $access_token = Cache::get($appid);
        } else {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
            $res = $this->https_request($url, 'get', 'json');
            $access_token = $res['access_token'];
            Cache::put($access_token, $appid, 100);
        }

        Log::info('获取微信access_token');
        Log::info($access_token);
        return $access_token;
    }

    
    //上传卡券图片（该方法只能获取到图片的URL。上传的图片限制文件大小限制1MB,仅支持JPG、PNG格式）
    public function mediaUploadImg(Request $request)
    {
        $token = $this->parseToken();
        $config_id = $request->post('configId', '1234');
        $filename = $request->post('fileName', '');
//        Log::info($filename); //https://test.yunsoyi.cn/upload/images/135629_116.png
//        Log::info(public_path()); // /www/wwwroot/test.yunsoyi.cn/public
        $file_path = str_replace(env('APP_URL'), public_path(), $filename);

        try {
            $check_data = [
                'fileName' => '图片地址'
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => '2',
                    'message' => $check
                ]);
            }

            $config = new WeixinConfigController();
            $config_obj = $config->weixin_config_obj($config_id);
            $config = [
                'app_id' => $config_obj->app_id,
                'secret' => $config_obj->app_secret
            ];
            $app = Factory::officialAccount($config);
            $res = $app->material->uploadImage($file_path);
            Log::info('上传卡券图片');
            Log::info($res);
//            $res = [
//                'media_id' => 'tODTFH4ptUi72OxH5Yb3LhKHW6V5iXqgy9-2tlppobs',
//                'url' => 'http://mmbiz.qpic.cn/sz_mmbiz_jpg/HarRlPYD70dKzUibKabicjfFtFmPYbEwkEBa1wQRWWDnLLOANcSpbebRG7HxuaHYplCkre44cSPjBQdHlMPggHOg/0?wx_fmt=jpeg',
//                'item' => [],
//            ];
            return json_encode([
                'status' => '1',
                'message' => '请求成功',
                'data' => $res
            ]);
        } catch (\Exception $ex) {
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }

    }
    
    
    //创建卡券
    public function createCard(Request $request)
    {
        $token = $this->parseToken();

        $store_id = $request->get('storeId', '');
        $config_id = $request->get('configId', '');
        $logo_url = $request->get('logoUrl', '');
        $location_id_list = $request->get('locationIdList', []);
        $card_type = $request->get('cardType', '');
        $code_type_text = $request->get('codeTypeText', '');
        $brand_name = $request->get('brandName', '');
        $title = $request->get('title', '');
        $color = $request->get('color', '');
        $notice = $request->get('notice', '');
        $description = $request->get('description', '');
        $quantity = $request->get('quantity', '');
        $date_info_type = $request->get('dateInfoType', '');
        $begin_timestamp = $request->get('beginTimestamp', '');
        $end_timestamp = $request->get('endTimestamp', '');
        $fixed_term = $request->get('fixedTerm', '');
        $fixed_begin_term = $request->get('fixedBeginTerm', '');
        $use_limit = $request->get('useLimit', 50);
        $get_limit = $request->get('getLimit', 50);
        $bind_openid = $request->get('bindOpenid', false);
        $can_share = $request->get('canShare', true);
        $can_give_friend = $request->get('canGiveFriend', false);
        $use_all_locations = $request->get('useAllLocations', '');
        $center_title = $request->get('centerTitle', '');
        $center_sub_title = $request->get('centerSubTitle', '');
        $center_url = $request->get('centerUrl', '');
        $custom_url_name = $request->get('customUrlName', '');
        $custom_url = $request->get('customUrl', '');
        $custom_url_sub_title = $request->get('customUrlSubTitle', '');
        $promotion_url_name = $request->get('promotionUrlName', '');
        $promotion_url = $request->get('promotionUrl', '');
        $service_phone = $request->get('servicePhone', '');
        $accept_category = $request->get('acceptCategory', '');
        $reject_category = $request->get('rejectCategory', '');
        $advanced_info_least_cost = $request->get('advancedInfoLeastCost', '');
        $object_use_for = $request->get('objectUseFor', '');
        $can_use_with_other_discount = $request->get('canUseWithOtherDiscount', true);
        $abstract = $request->get('abstract', '');
        $icon_url_list = $request->get('iconUrlList', '');
        $text_image_list = $request->get('textImageList', []); ///图文列表,显示在详情内页,优惠券须至少传入一组图文列表：[image_url, text]
        $time_limit_type = $request->get('timeLimitType', '');
        $begin_hour = $request->get('beginHour', '');
        $end_hour = $request->get('endHour', '');
        $begin_minute = $request->get('beginMinute', '');
        $end_minute = $request->get('endMinute', '');
        $business_service = $request->get('businessService', '');
        $deal_detail = $request->get('dealDetail', '');
        $least_cost = $request->get('leastCost', '');
        $reduce_cost = $request->get('reduceCost', '');
        $discount = $request->get('discount', '');
        $gift = $request->get('gift', '');
        $default_detail = $request->get('defaultDetail', '');

        try {
            $check_data = [
                'logoUrl' => '卡券的商户logo',
                'cardType' => '卡券类型',
                'codeTypeText' => '码型',
                'brandName' => '商户名字',
                'title' => '卡券名',
                'description' => '卡券使用说明',
                'quantity' => '卡券库存的数量',
                'dateInfoType' => '卡券限制时间类型'
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => '2',
                    'message' => $check
                ]);
            }

            //TODO：资料入库

            $access_token = $this->get_access_token($config_id);
            $url = "https://api.weixin.qq.com/card/create?access_token=".$access_token;
            $requestData = [
                'card' => [
                    'card_type' => $card_type, //卡券类型：GROUPON-团购券；CASH-代金券；DISCOUNT-折扣券；GIFT-兑换券；GENERAL_COUPON-优惠券
                    'groupon' => [
                        'base_info' => [
                            'logo_url' => $logo_url, //卡券的商户logo,建议像素为300*300
                            'code_type' => $code_type_text, //码型：'CODE_TYPE_TEXT'文本；'CODE_TYPE_BARCODE'一维码；CODE_TYPE_QRCODE'二维码；'CODE_TYPE_ONLY_QRCODE'二维码无code显示；'CODE_TYPE_ONLY_BARCODE'一维码无code显示；'CODE_TYPE_NONE'不显示code和条形码类型
                            'brand_name' => $brand_name, //商户名字,字数上限为12个汉字
                            'title' => $title, //卡券名,字数上限为9个汉字(建议涵盖卡券属性、服务及金额)
                            'color' => $color, //券颜色。按色彩规范标注填写Color010-Color100
                            'notice' => $notice, //卡券使用提醒,字数上限为16个汉字
                            'description' => $description, //卡券使用说明,字数上限为1024个汉字
                            'sku' => [
                                'quantity' => $quantity //卡券库存的数量,上限为100000000
                            ],
                            'date_info' => [
                                'type' => $date_info_type, //使用时间的类型,DATE_TYPE_FIXTIME_RANGE,表示固定日期区间;DATE_TYPEFIX_TERM,表示固定时长(自领取后按天算)
                                'begin_timestamp' => $date_info_type=='DATE_TYPE_FIX_TIME_RANGE' ? strtotime($begin_timestamp) : 0, //type为DATE_TYPE_FIX_TIME_RANGE时专用,表示起用时间。从1970年1月1日00:00:00至起用时间的秒数,最终需转换为字符串形态传入(东八区时间,UTC+8,单位为秒).时间须早于2038年1月19日
                                'end_timestamp' => $date_info_type=='DATE_TYPE_FIX_TIME_RANGE' ? strtotime($end_timestamp) : 0, //表示结束时间,建议设置为截止日期的23:59:59过期(东八区时间,UTC+8,单位为秒).时间须早于2038年1月19日
                                'fixed_term' => $date_info_type=='DATE_TYPE_FIX_TERM' ? $fixed_term: 0, //type为DATE_TYPE_FIX_TERM时专用,表示自领取后多少天内有效,不支持填写0（单位为天）
                                'fixed_begin_term' => $date_info_type=='DATE_TYPE_FIX_TERM' ? $fixed_begin_term: 0 //type为DATE_TYPE_FIX_TERM时专用,表示自领取后多少天开始生效,领取后当天生效填写0（单位为天）
                            ],
                            'use_custom_code' => false, //否,是否自定义Code码.填写true或false,默认为false
                            'location_id_list' => $location_id_list, //门店位置poiid,调用 POI门店管理接口获取门店位置poiid。具备线下门店的商户为必填
                            'use_all_locations' => $use_all_locations //设置本卡券支持全部门店,与location_id_list互斥
                        ],
                        'advanced_info' => [
                            'use_condition' => [
                                'accept_category' => $card_type=='CASH' ? $accept_category : '', //指定可用的商品类目,仅用于代金券类型,填入后将在券面拼写适用于xxx
                                'reject_category' => $card_type=='CASH' ? $reject_category : '', //指定不可用的商品类目,仅用于代金券类型,填入后将在券面拼写不适用于xxxx
                                'least_cost' => ($card_type=='CASH' || $card_type=='GIFT') ? $advanced_info_least_cost : '', //满减门槛字段,可用于兑换券和代金券,填入后将在全面拼写消费满xx元可用
                                'object_use_for' => $card_type=='GIFT' ? $object_use_for : '', //购买xx可用类型门槛,仅用于兑换,填入后自动拼写购买xxx可用
                                'can_use_with_other_discount' => $can_use_with_other_discount //不可以与其他类型共享门槛,填写false时系统将在使用须知里拼写“不可与其他优惠共享”,填写true时系统将在使用须知里拼写“可与其他优惠共享”,默认为true
                            ]
                        ]
                    ]
                ]
            ];
            if ($card_type == 'GROUPON') {
                $requestData['card']['groupon']['deal_detail'] = $deal_detail; //团购券专用,团购详情
            }
            if ($card_type == 'CASH') {
                $requestData['card']['groupon']['least_cost'] = $least_cost; //代金券专用,表示起用金额（单位为分）,如果无起用门槛则填0
                $requestData['card']['groupon']['reduce_cost'] = $reduce_cost; //代金券专用,表示减免金额。（单位为分）
            }
            if ($card_type == 'DISCOUNT') {
                $requestData['card']['groupon']['discount'] = $discount; //折扣券专用,表示打折额度（百分比）。填30就是七折
            }
            if ($card_type == 'GIFT') {
                $requestData['card']['groupon']['gift'] = $gift; //兑换券专用,填写兑换内容的名称。eg:可兑换音乐木盒一个
            }
            if ($card_type == 'GENERAL_COUPON') {
                $requestData['card']['groupon']['default_detail'] = $default_detail; //优惠券专用,填写优惠详情。eg:音乐木盒
            }
            if ($use_limit) {
                $requestData['card']['groupon']['base_info']['use_limit'] = $use_limit; //否,每人可核销的数量限制,不填写默认为50
            }
            if ($get_limit) {
                $requestData['card']['groupon']['base_info']['get_limit'] = $get_limit; //否,每人可领券的数量限制,不填写默认为50
            }
            if ($bind_openid) {
                $requestData['card']['groupon']['base_info']['bind_openid'] = $bind_openid; //否,是否指定用户领取,填写true或false,默认为false
            }
            if ($can_share) {
                $requestData['card']['groupon']['base_info']['can_share'] = $can_share; //否,卡券领取页面是否可分享
            }
            if ($can_give_friend) {
                $requestData['card']['groupon']['base_info']['can_give_friend'] = $can_give_friend; //否,卡券是否可转赠
            }
            if ($center_title) {
                $requestData['card']['groupon']['base_info']['center_title'] = $center_title ?? '立即使用'; //否,卡券顶部居中的按钮,仅在卡券状态正常(可以核销)时显示
            }
            if ($center_sub_title) {
                $requestData['card']['groupon']['base_info']['center_sub_title'] = $center_sub_title ?? '立即享受优惠'; //否,显示在入口下方的提示语 ,仅在卡券状态正常(可以核销)时显示
            }
            if ($center_url) {
                $requestData['card']['groupon']['base_info']['center_url'] = $center_url ?? 'www.qq.com'; //否,顶部居中的url,仅在卡券状态正常(可以核销)时显示
            }
            if ($custom_url_name) {
                $requestData['card']['groupon']['base_info']['custom_url_name'] = $custom_url_name ?? '立即使用'; //否,自定义跳转外链的入口名字
            }
            if ($custom_url) {
                $requestData['card']['groupon']['base_info']['custom_url'] = $custom_url ?? 'http://www.qq.com'; //否,自定义跳转的URL
            }
            if ($custom_url_sub_title) {
                $requestData['card']['groupon']['base_info']['custom_url_sub_title'] = $custom_url_sub_title ?? '更多惊喜'; //否,显示在入口右侧的提示语,6个汉字以内
            }
            if ($promotion_url_name) {
                $requestData['card']['groupon']['base_info']['promotion_url_name'] = $promotion_url_name ?? '更多优惠'; //否,营销场景的自定义入口名称
            }
            if ($promotion_url) {
                $requestData['card']['groupon']['base_info']['promotion_url'] = $promotion_url ?? 'http://www.qq.com'; //否,入口跳转外链的地址链接
            }
            if ($service_phone) {
                $requestData['card']['groupon']['base_info']['service_phone'] = $service_phone; //否,客服电话
            }
            if ($abstract && $icon_url_list) {
                $requestData['card']['groupon']['advanced_info']['abstract']['abstract'] = $abstract; //封面摘要简介
                $requestData['card']['groupon']['advanced_info']['abstract']['icon_url_list'] = $icon_url_list; //封面图片列表,仅支持填入一个封面图片链接,上传图片接口上传获取图片获得链接,填写非CDN链接会报错,并在此填入。建议图片尺寸像素850*350
            }
            if ($text_image_list != [] && !empty($text_image_list)) {
                $requestData['card']['groupon']['advanced_info']['text_image_list'] = [$text_image_list]; //图文列表,显示在详情内页,优惠券须,至少传一组图文列表
            }
            if ($business_service) {
                $requestData['card']['groupon']['advanced_info']['business_service'] = [$business_service]; //商家服务类型： BIZ_SERVICE_DELIVER 外卖服务； BIZ_SERVICE_FREE_PARK 停车位； BIZ_SERVICE_WITH_PET 可带宠物； BIZ_SERVICE_FREE_WIFI 免费wifi, 可多选
            }
            if ($time_limit_type) {
                $requestData['card']['groupon']['advanced_info']['time_limit']['type'] = $time_limit_type; //限制类型枚举值：支持填入MONDAY周一 TUESDAY周二 WEDNESDAY周三 THURSDAY周四 FRIDAY周五 SATURDAY周六 SUNDAY周日 此处只控制显示,不控制实际使用逻辑,不填默认不显示
            }
            if ($begin_hour) {
                $requestData['card']['groupon']['advanced_info']['time_limit']['begin_hour'] = $begin_hour; //当前type类型下的起始时间（小时） ,如当前结构体内填写了MONDAY, 此处填写了10,则此处表示周一 10:00可用
            }
            if ($end_hour) {
                $requestData['card']['groupon']['advanced_info']['time_limit']['end_hour'] = $end_hour; //当前type类型下的结束时间（小时） ,如当前结构体内填写了MONDAY, 此处填写了20, 则此处表示周一 10:00-20:00可用
            }
            if ($begin_minute) {
                $requestData['card']['groupon']['advanced_info']['time_limit']['begin_minute'] = $begin_minute; //当前type类型下的起始时间（分钟） ,如当前结构体内填写了MONDAY, begin_hour填写10,此处填写了59, 则此处表示周一 10:59可用
            }
            if ($end_minute) {
                $requestData['card']['groupon']['advanced_info']['time_limit']['end_minute'] = $end_minute; //当前type类型下的结束时间（分钟） ,如当前结构体内填写了MONDAY, begin_hour填写10,此处填写了59, 则此处表示周一 10:59-00:59可用
            }
            Log::info('微信卡券-创建卡券入参');
            Log::info($requestData);
            Log::info($url);
            $res = $this->https_request($url, $requestData, 'post');

            if (isset($res['errcode']) && $res['errcode'] == 0) {
                return json_encode([
                    'status' => '1',
                    'message' => '创建成功',
                    'data' => $res['card_id']
                ]);
            } else {
                return json_encode([
                    'status' => '2',
                    'code' => $res['errcode'],
                    'message' => $this->getMessageByCode($res['errcode'])
                ]);
            }
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }
    
    
    //创建货架
    public function createCardLandingpage(Request $request)
    {
        $config_id = $request->post('configId', '');
        $banner = $request->post('banner', '');
        $title = $request->post('title', '');
        $can_share = $request->post('canShare', '');
        $scene = $request->post('scene', '');
        $card_list = $request->post('cardList', ''); //json, card_id所要在页面投放的card_id; thumb_url缩略图url

        $access_token = $this->get_access_token($config_id);
        $url = "https://api.weixin.qq.com/card/landingpage/create?access_token=".$access_token;

//        $card_list = json_decode($card_list, true);

        try {
            $requestData = [
                'banner' => $banner, //页面的banner图片链接，须调用，建议尺寸为640*300
                'title' => $title, //页面的title
                'can_share' => $can_share, //页面是否可以分享
                'scene' => $scene, //投放页面的场景值：SCENE_NEAR_BY 附近，SCENE_MENU 自定义菜单，SCENE_QRCODE 二维码，SCENE_ARTICLE 公众号文章，SCENE_H5 h5页面，SCENE_IVR 自动回复，SCENE_CARD_CUSTOM_CELL 卡券自定义cell
                'card_list' => [$card_list] //卡券列表:card_id所要在页面投放的card_id; thumb_url缩略图url
            ];
            Log::info('投放卡券-创建货架-入参');
            Log::info($url);
            Log::info($requestData);
            $res = $this->https_request($url, $requestData, 'post');
            if ($res['errcode'] == 0) {
                return json_encode([
                    'status' => '1',
                    'message' => '创建成功',
                    'data' => $res
                ]);
            } else {
                return json_encode([
                    'status' => '2',
                    'message' => $this->getMessageByCode($res['errcode']),
                    'errcode' => $res['errcode'],
                    'data' => $res
                ]);
            }
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    //查询code
    public function getCardCode(Request $request)
    {
        $config_id = $request->get('configId', '');
        $code = $request->get('code', '');
        $card_id = $request->get('cardId', '');
        $check_consume = $request->get('checkConsume', true);

        $access_token = $this->get_access_token($config_id);
        try {
            $url = "https://api.weixin.qq.com/card/code/get?access_token=".$access_token;
            $requestData = [
                'code' => $code //单张卡券的唯一标准
            ];
            if ($card_id) $requestData['card_id'] = $card_id; //否，卡券ID代表一类卡券,自定义code卡券必填
            if ($check_consume) $requestData['check_consume'] = $check_consume ? true : false; //否，是否校验code核销状态，填入true和false时的code异常状态返回数据不同
            $res = $this->https_request($url, $requestData, 'post');
            Log::info('查询code');
            Log::info($url);
            Log::info($requestData);
            Log::info($res);
            if ($res['errcode'] == 0) {
                $sucData = [
                    'card_id' => $res['card']['card_id'], //卡券ID
                    'begin_time' => date('Y-m-d H:i:s', strtotime($res['card']['begin_time'])), //起始使用时间
                    'end_time' => date('Y-m-d H:i:s', strtotime($res['card']['end_time'])), //结束时间
                    'openid' => $res['openid'], //用户openid
                    'can_consume' => $res['can_consume'], //是否可以核销
                    'user_card_status' => $this->getUserCardsStatus($res['user_card_status']), //当前code对应卡券的状态
                ];
                return json_encode([
                    'status' => '1',
                    'message' => '查询成功',
                    'data' => $sucData
                ]);
            } else {
                if ($check_consume) {
                    return json_encode([
                        'status' => '2',
                        'message' => $this->getMessageByCode($res['errcode'])
                    ]);
                } else {
                    return json_encode([
                        'status' => '2',
                        'message' => $this->getUserCardsStatus($res['user_card_status']),
                        'can_consume' => $res['can_consume'] //是否可以核销
                    ]);
                }
            }
        } catch (\Exception $ex) {
            return [
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //获取用户已领取卡券
    public function getCardList(Request $request)
    {
        $config_id = $request->post('config_id', '');
        $openid = $request->post('openId', '');
        $card_id = $request->post('cardId', '');

        $access_token = $this->get_access_token($config_id);
        $url = "https://api.weixin.qq.com/card/user/getcardlist?access_token=".$access_token;

        $requestData = [
            'openid' => $openid //需要查询的用户openid
        ];
        if ($card_id) $requestData['card_id'] = $card_id; //卡券ID。不填写时默认查询当前appid下的卡券

        try {
            $res = $this->https_request($url, $requestData, 'post');
            Log::info('获取用户已领取卡券');
            Log::info($url);
            Log::info($requestData);
            Log::info($res);
            if ($res['errcode'] == 0) {
                return json_encode([
                    'status' => '1',
                    'message' => '查询成功',
                    'data' => [
                        'card_list' => $res['card_list'], //卡券列表
                        'has_share_card' => $res['has_share_card'] //是否有可用的朋友的券
                    ]
                ]);
            } else {
                return json_encode([
                    'status' => '2',
                    'message' => $this->getMessageByCode($res['errcode'])
                ]);
            }
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    //查看卡券详情
    public function getCardInfo(Request $request)
    {
        $config_id = $request->get('configId', '');
        $card_id = $request->get('cardId', '');

        $access_token = $this->get_access_token($config_id);
        $url = "https://api.weixin.qq.com/card/get?access_token=".$access_token;

        $requestData = [
            'card_id' => $card_id //卡券ID
        ];

        try {
            $res = $this->https_request($url, $requestData, 'post');
            Log::info('查看卡券详情');
            Log::info($url);
            Log::info($requestData);
            Log::info($res);
            if ($res['errcode'] == 0) {
                return json_encode([
                    'status' => '1',
                    'message' => '查询成功',
                    'data' => $res
                ]);
            } else {
                return json_encode([
                    'status' => '2',
                    'message' => $this->getMessageByCode($res['errcode']),
                    'data' => $res
                ]);
            }

        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    //批量查询卡券列表
    public function getCardBatch(Request $request)
    {
        $config_id = $request->get('configId', '');
        $offset = $request->get('offset', '');
        $count = $request->get('count', '');
        $status_list = $request->get('statusList', []);

        $access_token = $this->get_access_token($config_id);
        $url = "https://api.weixin.qq.com/card/batchget?access_token=".$access_token;

        $requestData = [
            'offset' => $offset, //查询卡列表的起始偏移量，从0开始，即offset: 5是指从从列表里的第六个开始读取
            'count' => $count //需要查询的卡片的数量（数量最大50）
        ];

        try {
            if ($status_list && ($status_list != [])) $requestData['status_list'] = $status_list; //否，支持开发者拉出指定状态的卡券列表,CARD_STATUS_NOT_VERIFY-待审核,CARD_STATUS_VERIFY_FAIL-审核失败,CARD_STATUS_VERIFY_OK- 通过审核,CARD_STATUS_DELETE-卡券被商户删除,CARD_STATUS_DISPATCH-在公众平台投放过的卡券
            $res = $this->https_request($url, $requestData, 'post');
            Log::info('批量查询卡券列表');
            Log::info($url);
            Log::info($requestData);
            Log::info($res);
            if ($res['errcode'] == 0) {
                return json_encode([
                    'status' => '1',
                    'message' => '查询成功',
                    'data' => [
                        'card_id_list' => $res['card_id_list'], //卡券ID列表
                        'total_num' => $res['total_num'] //该商户名下卡券ID总数
                    ]
                ]);
            } else {
                return json_encode([
                    'status' => '2',
                    'message' => $this->getMessageByCode($res['errcode'])
                ]);
            }

        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    //统计卡券数据
    public function getCardBizuinInfo(Request $request)
    {
        $config_id = $request->get('configId', '');
        $begin_date = $request->get('begin_date', ''); //2015-06-15
        $end_date = $request->get('end_date', ''); //2015-06-30
        $cond_source = $request->get('cond_source', 0);

        $access_token = $this->get_access_token($config_id);
        $url = "https://api.weixin.qq.com/datacube/getcardbizuininfo?access_token=".$access_token;
        $requestData = [
            'begin_date' => $begin_date, //查询数据的起始时间
            'end_date' => $end_date, //查询数据的截至时间
            'cond_source' => $cond_source //卡券来源，0为公众平台创建的卡券数据 、1是API创建的卡券数据
        ];

        try {
            $res = $this->https_request($url, $requestData, 'post');
            if ($res['errcode'] == 0) {
                return json_encode([
                    'status' => '1',
                    'message' => '查询成功',
                    'data' => $res
                ]);
            } else {
                return json_encode([
                    'status' => '2',
                    'message' => $this->getMessageByCode($res['errcode'])
                ]);
            }

        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    //核销Code
    public function consumeCardCode(Request $request)
    {
        $config_id = $request->get('configId', '');
        $code = $request->get('code', '');
        $card_id = $request->get('cardId', '');

        $access_token = $this->get_access_token($config_id);
        $url = "https://api.weixin.qq.com/card/code/consume?access_token=".$access_token;
        try {
            $requestData = [
                'code' => $code //需核销的Code码
            ];
            if ($card_id) $requestData['card_id'] = $card_id; //卡券ID。创建卡券时use_custom_code填写true时必填。非自定义Code不必填写
            $res = $this->https_request($url, $requestData, 'post');
            if ($res['errcode'] == 0) {
                return json_encode([
                    'status' => '1',
                    'message' => '核销成功',
                    'data' => [
                        'card_id' => $res['card']['card_id'],
                        'openid' => $res['openid']
                    ]
                ]);
            } else {
                return json_encode([
                    'status' => '2',
                    'message' => $this->getMessageByCode($res['errcode'])
                ]);
            }
        } catch (\Exception $ex) {
            return json_encode([
                'status' => '-1',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    //
    function getQRTicket(Request $request)
    {
        $access_token = $this->get_access_token();
        $requestData = [
            "action_name" => "QR_CARD",
            "expire_seconds" => 1800,
            "action_info" => [
                "card" => [
                    "card_id" => "'.$card_id.'",
                    "code" => "1234567890",
                    "openid" => "",
                    "is_unique_code" => false ,
                    "outer_str" => ""
                ]
            ]
        ];
        $url = "https=>//api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
        $res = $this->https_request( $url ,'post', 'json', $requestData);

        echo "<img src='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$res['ticket']}' />";
        print_r($res);exit();
    }


    //
    function wxCardWhiteList(Request $request)
    {
        $access_token = $this->get_access_token();
        $url = "https://api.weixin.qq.com/card/testwhitelist/set?access_token=".$access_token;
        $requestData = [
            'openid' => ['oG7Sh1R_j1bAmj_yz3jsAK5-Uep4']
        ];
        $res = $this->https_request($url, 'post', 'json', $requestData);
//        print_r($res);

        return $res;
    }


    //获取免费券数据接口
    function getCardCardInfo(Request $request)
    {
        $begin_date = $request->post('beginDate', '');
        $end_date = $request->post('endDate', '');
        $cond_source = $request->post('condSource', 0);
        $card_id = $request->post('cardId', '');
        $config_id = $request->post('configId', '');

        $check_data = [
            'beginDate' => '起始时间',
            'endDate' => '截止时间'
        ];
        $check = $this->check_required($request->except(['token']), $check_data);
        if ($check) {
            return json_encode([
                'status' => '2',
                'message' => $check
            ]);
        }

        if (strtotime($end_date) >= strtotime(date('Y-m-d 00:00:00', time()))) {
            return json_encode([
                'status' => '2',
                'message' => '只能拉取当天之前的数据'
            ]);
        }

        $day = 62;
        $limit_day = floor((strtotime($end_date) - strtotime($begin_date))/86400 + 1);
        if ($limit_day > $day) {
            return json_encode([
                'status' => '2',
                'message' => '查询时间区间需<=62天'
            ]);
        }

        $begin_date = date('Y-m-d', strtotime($begin_date));
        $end_date = date('Y-m-d', strtotime($end_date));
        $access_token = $this->get_access_token($config_id);
        $url = "https://api.weixin.qq.com/datacube/getcardcardinfo?access_token=".$access_token;
        $requestData = [
            'begin_date' => $begin_date,
            'end_date' => $end_date,
            'cond_source' => $cond_source
        ];
        if ($card_id) $requestData['card_id'] = $card_id;
        $res = $this->https_request($url, $requestData, 'post');
        Log::info('获取免费券数据接口');
        Log::info($url);
        Log::info($requestData);
        Log::info($res);

        return json_encode([
            'status' => '1',
            'message' => '查询成功',
            'data' => $res['list'] ?? $res
        ]);
    }


    //获取微信access_token
    protected function get_access_token22($config_id = '1234')
    {
        $config = new WeixinConfigController();
        $config_obj = $config->weixin_config_obj($config_id);
        $config = [
            'app_id' => $config_obj->app_id,
            'secret' => $config_obj->app_secret
        ];
        $app = Factory::officialAccount($config);
        $access_token = $app->access_token->getToken();
        Log::info('获取微信access_token');
        Log::info($access_token);
//        $access_token = [
//            "access_token" => "36_eCT17TgosUilssgysYlci1dthzpijvt8YFKsIp91sdLIG-HFzC1ve6xSfRFc9mddJkCAkqYBMzdir-Li9xq_LqPFmFyicIRuZnFfBI4mX5fxoLYhkIR9xEu6YJtYGKVMKr-UI3x04JMmVgohSJJbAJAJAA",
//            "expires_in" => 7200
//        ];

        return $access_token['access_token'];
    }


    //卡券背景色
    public function getWXCardBgColor()
    {
        return json_encode([
            'status' => '1',
            'message' => '返回成功',
            'data' => [
                '#63b359' => 'Color010',
                '#2c9f67' => 'Color020',
                '#509fc9' => 'Color030',
                '#5885cf' => 'Color040',
                '#9062c0' => 'Color050',
                '#d09a45' => 'Color060',
                '#e4b138' => 'Color070',
                '#ee903c' => 'Color080',
                '#f08500' => 'Color081',
                '#a9d92d' => 'Color082',
                '#dd6549' => 'Color090',
                '#cc463d' => 'Color100',
                '#cf3e36' => 'Color101',
                '#5E6671' => 'Color102'
            ]
        ]);
    }


    //卡券类型
    public function getWXCardType()
    {
        return json_encode([
            'status' => '1',
            'message' => '返回成功',
            'data' => [
                '团购券' => 'GROUPON',
                '代金券' => 'CASH',
                '折扣券' => 'DISCOUNT',
                '兑换券' => 'GIFT',
                '优惠券' => 'GENERAL_COUPON'
            ]
        ]);
    }


    //码型
    public function getWXCardCodeType()
    {
        return json_encode([
            'status' => '1',
            'message' => '返回成功',
            'data' => [
                '文本' => 'CODE_TYPE_TEXT',
                '一维码' => 'CODE_TYPE_BARCODE',
                '二维码' => 'CODE_TYPE_QRCODE',
                '二维码无code显示' => 'CODE_TYPE_ONLY_QRCODE',
                '一维码无code显示' => 'CODE_TYPE_ONLY_BARCODE',
                '不显示code和条形码类型' => 'CODE_TYPE_NONE'
            ]
        ]);
    }


    //获取卡券状态
    protected function getUserCardsStatus($status)
    {
        switch ($status) {
            case 'NORMAL':  return '正常';  break;
            case 'CONSUMED':  return '已核销';  break;
            case 'EXPIRE':  return '已过期';  break;
            case 'GIFTING':  return '转赠中';  break;
            case 'GIFT_TIMEOUT':  return '转赠超时';  break;
            case 'DELETE':  return '已删除';  break;
            case 'UNAVAILABLE':  return '已失效';  break;
            case 'invalid serial code':  return 'code未被添加或被转赠领取';  break;
            default:  return '状态未知';
        }
    }


    //获取卡券错误码信息
    protected function getMessageByCode($errCode)
    {
        switch ($errCode) {
            case '-1':  return '系统繁忙，此时请开发者稍后再试';  break;
            case '40001':  return '无效凭证，访问令牌无效或不是最新提示';  break;
            case '40009':  return '图片文件超长';  break;
            case '40013':  return '不合法的Appid，请开发者检查AppID的正确性，避免异常字符，注意大小写';  break;
            case '40053':  return '不合法的actioninfo，请开发者确认参数正确';  break;
            case '40071':  return '不合法的卡券类型';  break;
            case '40072':  return '不合法的编码方式';  break;
            case '40073':  return '卡号无效';  break;
            case '40078':  return '不合法的卡券状态';  break;
            case '40079':  return '不合法的时间';  break;
            case '40080':  return '不合法的CardExt';  break;
            case '40099':  return '卡券已被核销';  break;
            case '40100':  return '不合法的时间区间';  break;
            case '40116':  return '不合法的Code码';  break;
            case '40122':  return '不合法的库存数量';  break;
            case '40124':  return '会员卡设置查过限制的custom_field字段';  break;
            case '40127':  return '卡券被用户删除或转赠中';  break;
            case '41012':  return '缺少cardid参数';  break;
            case '45030':  return '该cardid无接口权限';  break;
            case '45031':  return '库存为0';  break;
            case '45033':  return '用户领取次数超过限制get_limit';  break;
            case '41011':  return '缺少必填字段';  break;
            case '45021':  return '字段超过长度限制，请参考相应接口的字段说明';  break;
            case '40056':  return '不合法的Code码';  break;
            case '43009':  return '无自定义SN权限，请前往公众平台申请';  break;
            case '43010':  return '无储值权限，请前往公众平台申请';  break;
            default:  return '错误码信息未知，请前往公众平台查看';
        }
    }


}
